package userServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swim2.entitybeans.User;
import swim2.sessionbeans.*;

public class FriendRequestAnswerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public FriendRequestAnswerServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		
		try{
			Context ctx = getInitialContext();			
			UserSystemRemote userSystemRemote = (UserSystemRemote) ctx.lookup("userJNDI");
			int userId = Integer.parseInt(request.getParameter("userId"));
			int reqId = Integer.parseInt(request.getParameter("reqId"));
			int answer = Integer.parseInt(request.getParameter("answer"));
			String senderName = request.getParameter("senderName");
			String userMail = userSystemRemote.getMail(userId);
			String userPassword = userSystemRemote.getPassword(userId);
			ArrayList<User> suggestion = new ArrayList<User>();
			if(answer==1) {
				userSystemRemote.insertFriendship(reqId);
				int suggested = userSystemRemote.getSuggested(reqId);
				if(suggested == 0) {
					suggestion = (ArrayList <User>) userSystemRemote.findSuggestion(reqId, userId);
					for (int i = 5; i < suggestion.size(); i++) {
						suggestion.remove(i);
						i--;
					}
				}
			}
			else if(answer==0) userSystemRemote.deleteFriendRequest(reqId);
			
			request.setAttribute("userId", userId);
			request.setAttribute("userMail", userMail);
			request.setAttribute("userPassword", userPassword);
			request.setAttribute("answer", answer);
			request.setAttribute("senderName", senderName);
			request.setAttribute("suggestion", suggestion);
			RequestDispatcher dispatcher =
			request.getRequestDispatcher("/UserJsp/FriendRequestAnswer.jsp");
			dispatcher.forward(request, response);	
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("user panel exception");
		}
	}

	static public Context getInitialContext() throws Exception{
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL, "localhost:1099");
		return new InitialContext(env);
	}
}
